//
//  HXSelectedAreaMapViewController.m
//  KD
//
//  Created by ifly on 16/3/17.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXSelectedAreaMapViewController.h"

@interface HXSelectedAreaMapViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>{

    BMKPointAnnotation * _pointAnnotation;
}
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property(nonatomic,assign) BMKCoordinateSpan span;
@property(nonatomic,strong) BMKLocationService *location;
@property(nonatomic,assign) CLLocationCoordinate2D userLocation;
@property(nonatomic,assign) BOOL isYetLocation;//是否定位过
@property(nonatomic,assign) BOOL isLocationError;//是否定位失败
@property(nonatomic,strong) NSMutableDictionary *addressDict;

@property (nonatomic,assign) CLLocationCoordinate2D lastCoordinate;//上一次点击的经纬度

@end

@implementation HXSelectedAreaMapViewController

/**
 
 添加大头针
 
 */



- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.mapEnumType == MapTypeMeetingType) {
        
        self.navigationItem.title = @"长按选择会议地点";
    }else if (self.mapEnumType == MapTypeChangeCoordinateType){
    
        self.navigationItem.title = @"长按选择项目坐标";
    }
    self.mapView.delegate = self;
    self.isLocationError = NO;
    self.isYetLocation = NO;
    self.mapView.showsUserLocation = YES;//显示定位图层
    [self location];
}


- (IBAction)userLocationBtnClick:(id)sender {
    if (self.isLocationError) {//定位失败
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"定位失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }else{
        BMKCoordinateSpan span = BMKCoordinateSpanMake(0.02093,0.03279);
        BMKCoordinateRegion region = BMKCoordinateRegionMake(self.userLocation, span);
        [self.mapView setRegion:region animated:YES];
    }
}

/**大头针视图*/
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{
   
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        static NSString *pinID = @"PIN";
        BMKPinAnnotationView *newAnnotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
        if (newAnnotationView == nil) {
            newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
        }
        newAnnotationView.annotation = annotation;
        newAnnotationView.animatesDrop = YES;
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.contentMode = UIViewContentModeRight;
        imageView.frame = CGRectMake(0, 0, 12, 16);
        imageView.image = [UIImage imageNamed:@"rightgo"];
        newAnnotationView.rightCalloutAccessoryView = imageView;
        
        return newAnnotationView;
    }
    return nil;
}


/**点击大头针时*/
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view{
    
    if (self.mapEnumType == MapTypeChangeCoordinateType) {
        
        [self.delegate location:self.addressDict];
        self.isSelectd = YES;
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)mapview:(BMKMapView *)mapView onLongClick:(CLLocationCoordinate2D)coordinate{
    
    if (self.mapEnumType == MapTypeChangeCoordinateType) {
        
        if (coordinate.latitude == _lastCoordinate.latitude && coordinate.longitude == _lastCoordinate.longitude) {
            
            self.isSelectd = YES;
            
        }else{
        
            self.isSelectd = NO;
        }
    }
    
    if (self.isSelectd) {
        return;
    }else{
        HXLog(@"'");
    }
    
    BMKGeoCodeSearch *searcher =[[BMKGeoCodeSearch alloc]init];
//    发起反向地理编码检索
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
    BMKReverseGeoCodeOption alloc]init];
    searcher.delegate = self;
    reverseGeoCodeSearchOption.reverseGeoPoint = coordinate;
    BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
      NSLog(@"反geo检索发送成功");
        [self.addressDict setObject:[NSString stringWithFormat:@"%.6f",coordinate.latitude] forKey:@"Y"];
        [self.addressDict setObject:[NSString stringWithFormat:@"%.6f",coordinate.longitude] forKey:@"X"];
        [SVProgressHUD showWithStatus:@"正在加载" ];
    }
    else
    {
      NSLog(@"反geo检索发送失败");
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }
    
    
    
    if (self.mapEnumType == MapTypeChangeCoordinateType) {
        
        _pointAnnotation = [[BMKPointAnnotation alloc] init];
        _pointAnnotation.coordinate = coordinate;
        [self.mapView addAnnotation:_pointAnnotation];
        _lastCoordinate = coordinate;
    }
    
}

//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
  if (error == BMK_SEARCH_NO_ERROR) {
//      在此处理正常结果
      [self.addressDict setObject:result.address forKey:@"address"];
      
#pragma mark ------
      if (self.mapEnumType == MapTypeMeetingType) {
     
        [self.delegate location:self.addressDict];
        self.isSelectd = YES;
        [self.navigationController popViewControllerAnimated:YES];
      }
      
      [SVProgressHUD dismiss];
  }
  else {
      [SVProgressHUD showErrorWithStatus:@"网络错误"];
      NSLog(@"抱歉，未找到结果");
  }
    
    _pointAnnotation.title = [self.addressDict objectForKey:@"address"];
}

#pragma mark - BMKLocationServiceDelegate
/**获得位置时*/
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);

    [self.mapView updateLocationData:userLocation];
    self.userLocation = userLocation.location.coordinate;
    
    if (self.isYetLocation) return;
    CLLocationCoordinate2D center = userLocation.location.coordinate;
    BMKCoordinateSpan span = BMKCoordinateSpanMake(0.021686, 0.014705);
    BMKCoordinateRegion region = BMKCoordinateRegionMake(center, span);
    [self.mapView setRegion:region animated:YES];
    
    self.isYetLocation = YES;
}
/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error{
    self.isLocationError = YES;
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"定位失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}


-(BMKLocationService *)location{
    if (!_location) {
        _location = [[BMKLocationService alloc]init];
        _location.delegate = self;
        [_location startUserLocationService];
    }
    return _location;
}

- (NSMutableDictionary *)addressDict{
    if (_addressDict == nil) {
        _addressDict = [[NSMutableDictionary alloc]init];
    }
    return _addressDict;
}
@end
